<script lang="ts" setup>
  import { ref, onMounted, computed } from 'vue';
  import _ from 'lodash';
  import { PlayerScore, HoleScore } from '@/types/game-score';
  import { CourseHole } from '@/types/course';
  import { GameSignImportItem } from '@/types/game';
  import { User } from '@/types/user';
  import {
    clearGameCaddie,
    getPlayerScore,
    queryCourseHole,
    confirmTotalScoreBatch,
  } from '@/api/game';
  import { api as viewerApi } from 'v-viewer';
  import { Message, Modal } from '@arco-design/web-vue';
  import { PlayerResults } from '@/config/game';
  // import GameSignImportResult from '@/views/game/components/game-sign-import-result.vue';
  import HoleScoreItem from './hole-score-item.vue';
  import HoleScoreBatchEditor from './hole-score-batch-editor.vue';
  import HoleScoreEditor from './hole-score-editor.vue';
  import ScoreConfirm from './score-confirm.vue';
  import HoleScoreImporter from './hole-score-importer.vue';
  import HoleScoreImportResult from './hole-score-import-result.vue';

  const props = defineProps<{
    gameId: string;
  }>();

  const list = ref<PlayerScore[]>([]);

  const holeList = ref<CourseHole[]>([]);
  const initHoleData = async () => {
    const res = await queryCourseHole(props.gameId);
    holeList.value = (res.data.data || []).sort(
      (a, b) => a.holeIndex - b.holeIndex
    );
  };

  const loading = ref(false);
  const initData = async () => {
    loading.value = true;
    const scoreRes = await getPlayerScore(props.gameId);
    list.value = scoreRes.data.data || [];
    loading.value = false;
  };

  const scoreType = ref('all');

  const filteredList = computed(() => {
    const newList = _.cloneDeep(list.value || []);

    if (scoreType.value !== 'all') {
      return newList.filter((p) => {
        // caddie_none, not_confirm, not18
        if (scoreType.value === 'caddie_none') {
          return !p.gameTotalScore || !p.gameTotalScore.caddieConfirm;
        }
        if (scoreType.value === 'not_confirm') {
          return !p.gameTotalScore || !p.gameTotalScore.confirm;
        }
        if (scoreType.value === 'not18') {
          return !p.gameHoleScores || p.gameHoleScores.length < 18;
        }
        if (scoreType.value === 'WD') {
          return p.gameTotalScore && p.gameTotalScore.playerResult === 2;
        }
        if (scoreType.value === 'DQ') {
          return p.gameTotalScore && p.gameTotalScore.playerResult === 3;
        }
        return true;
      });
    }

    return newList.sort((a, b) => {
      // 没有总成绩的，排在最后面
      if (!a.gameTotalScore && b.gameTotalScore) {
        return 1;
      }
      if (a.gameTotalScore && !b.gameTotalScore) {
        return -1;
      }
      if (a.gameTotalScore && b.gameTotalScore) {
        // @ts-ignore
        if (a.gameTotalScore.playerResult >= 2) {
          return 1;
        }
        // @ts-ignore
        if (b.gameTotalScore.playerResult >= 2) {
          return -1;
        }

        if (a.gameHoleScores && b.gameHoleScores) {
          if (a.gameHoleScores.length === b.gameHoleScores.length) {
            return a.gameTotalScore.total - b.gameTotalScore.total;
          }
          return b.gameHoleScores.length - a.gameHoleScores.length;
        }
      }
      return 0;
    });
  });

  onMounted(async () => {
    await initHoleData();

    await initData();
  });

  const holeScoreConfig = ref<{
    visible: boolean;
    player?: User;
    holeScore?: HoleScore;
    hole?: CourseHole;
  }>({
    visible: false,
  });

  const beginEditHoleScore = (
    hole: CourseHole,
    player: User,
    holeScore?: HoleScore
  ) => {
    holeScoreConfig.value = {
      visible: true,
      player,
      hole,
      holeScore,
    };
  };

  const handleEditDone = (refresh: boolean) => {
    if (refresh) {
      initData();
    }
    holeScoreConfig.value = {
      visible: false,
    };
  };

  const userHoleScoreConfig = ref<{
    visible: boolean;
    playerScore?: PlayerScore;
  }>({
    visible: false,
  });
  const beginEditUserHoleScore = (playerScore: PlayerScore) => {
    userHoleScoreConfig.value = {
      visible: true,
      playerScore,
    };
  };

  const handleUserScoreEditDone = (refresh: boolean) => {
    if (refresh) {
      initData();
    }
    userHoleScoreConfig.value = { visible: false };
  };

  const confirmConfig = ref<{
    visible: boolean;
    playerResult?: number;
    gameResult?: string;
    player?: User;
    pic?: string;
  }>({
    visible: false,
  });

  const beginConfirm = (
    player: User,
    pic?: string,
    gameResult?: string,
    playerResult?: number
  ) => {
    confirmConfig.value = {
      visible: true,
      player,
      pic,
      gameResult,
      playerResult,
    };
  };

  const showDetail = ref(true);

  const handleConfirmDone = (refresh: boolean) => {
    if (refresh) {
      initData();
    }
    confirmConfig.value = {
      visible: false,
    };
  };

  const viewConfirmPic = (player: PlayerScore) => {
    if (player.gameTotalScore && player.gameTotalScore.caddieConfirmPics) {
      try {
        const pics = JSON.parse(player.gameTotalScore.caddieConfirmPics);
        viewerApi({
          images: pics,
          options: {
            navbar: false,
          },
        });
      } catch (e) {
        viewerApi({
          images: [player.gameTotalScore.caddieConfirmPics],
          options: {
            navbar: false,
          },
        });
      }
    } else {
      Message.warning('球童未提交成绩');
    }
  };
  const clearingCaddie = ref(false);
  const handleClearCaddie = () => {
    Modal.confirm({
      title: '提示',
      content: '确认执行该操作？',
      async onBeforeOk() {
        await clearGameCaddie(props.gameId);
        Message.success('操作成功');
      },
    });
  };

  const importing = ref(false);
  const showSignImportResult = ref(false);
  const signImportItemList = ref<GameSignImportItem[]>([]);
  const handleImportSuccess = (data: GameSignImportItem[]) => {
    importing.value = false;
    showSignImportResult.value = true;
    initData();
    signImportItemList.value = data;
  };

  const handleBatchConfirm = () => {
    Modal.confirm({
      title: '提示',
      content: '该操作会将18洞成绩完整且设置了TEE台的球员的总成绩确认!',
      async onBeforeOk() {
        await confirmTotalScoreBatch(props.gameId);
        Message.success('操作成功');
        initData();
      },
    });
  };
</script>

<template>
  <div>
    <div style="margin-bottom: 12px">
      <a-space>
        <a-button :loading="loading" @click="initData">
          <template #icon><icon-refresh /></template>
          刷新
        </a-button>

        <a-switch v-model="showDetail">
          <template #checked>展示详情</template>
          <template #unchecked>隐藏详情</template>
        </a-switch>

        <a-radio-group
          v-model="scoreType"
          type="button"
          :options="[
            { label: '全部', value: 'all' },
            { label: '球童未提交', value: 'caddie_none' },
            { label: '待确认', value: 'not_confirm' },
            { label: '18洞成绩不完整', value: 'not18' },
            { label: 'WD', value: 'WD' },
            { label: 'DQ', value: 'DQ' },
          ]"
        />

        <a-button :loading="clearingCaddie" @click="handleClearCaddie">
          清空球童绑定关系
        </a-button>

        <a-button @click="importing = true">导入逐洞成绩</a-button>

        <a-button @click="handleBatchConfirm">批量确认成绩</a-button>
      </a-space>
    </div>
    <div class="group">
      <table :cellspacing="0" :cellpadding="0">
        <tr>
          <td rowspan="2" class="bold-bg cell1"> 成绩<br />核对 </td>
          <td rowspan="2" class="bold-bg cell2">球员</td>
          <td
            v-for="hole in holeList.filter((i) => i.holeType === 0)"
            :key="hole.id"
            class="bold-bg"
          >
            {{ hole.holeIndex }}
          </td>
          <td rowspan="2" class="bold-bg cell-t">OUT</td>
          <td
            v-for="hole in holeList.filter((i) => i.holeType === 1)"
            :key="hole.id"
            class="bold-bg"
          >
            {{ hole.holeIndex }}
          </td>
          <td rowspan="2" class="bold-bg cell-t">IN</td>
          <td rowspan="2" class="bold-bg cell-t">总杆</td>
          <td rowspan="2" class="bold-bg cell-t">净杆</td>
        </tr>
        <tr>
          <td v-for="hole in holeList" :key="hole.id" class="has-right-border">
            {{ hole.par }}
          </td>
        </tr>
        <template v-for="(player, index) in filteredList" :key="player.id">
          <tr>
            <td
              :rowspan="showDetail ? 6 : 1"
              class="check"
              :class="{ 'no-border-bottom': index + 1 === filteredList.length }"
            >
              <a-tooltip
                v-if="!player.gameTotalScore?.caddieConfirm"
                content="待球童确认"
              >
                <a
                  @click="
                    beginConfirm(
                      player,
                      player.gameTotalScore?.caddieConfirmPics,
                      player.gameTotalScore?.gameResult,
                      player.gameTotalScore?.playerResult
                    )
                  "
                >
                  <icon-calendar-clock />
                </a>
              </a-tooltip>
              <a-tooltip
                v-else-if="!player.gameTotalScore?.confirm"
                content="待确认，点击进行确认"
              >
                <a
                  @click="
                    beginConfirm(
                      player,
                      player.gameTotalScore?.caddieConfirmPics,
                      player.gameTotalScore?.gameResult,
                      player.gameTotalScore?.playerResult
                    )
                  "
                >
                  <icon-check />
                </a>
              </a-tooltip>
              <a-tooltip v-else content="已确认">
                <a
                  @click="
                    beginConfirm(
                      player,
                      player.gameTotalScore?.caddieConfirmPics,
                      player.gameTotalScore?.gameResult,
                      player.gameTotalScore?.playerResult
                    )
                  "
                >
                  <icon-check-circle-fill
                    style="color: rgb(var(--green-7)); font-size: 16px"
                  />
                </a>
              </a-tooltip>

              <span
                v-if="
                  player.gameTotalScore &&
                  player.gameTotalScore.playerResult &&
                  player.gameTotalScore.playerResult !== 1
                "
                class="player-result"
              >
                {{
                  PlayerResults[player.gameTotalScore.playerResult - 1].label
                }}
              </span>
            </td>
            <td
              :rowspan="showDetail ? 6 : 1"
              class="tee"
              :class="{ 'no-border-bottom': index + 1 === filteredList.length }"
            >
              <span
                :class="
                  player.gameTotalScore?.teeType
                    ? ['black', 'gold', 'blue', 'white', 'red', 'purple'][
                        parseInt(player.gameTotalScore.teeType, 10) + 1
                      ]
                    : ''
                "
              />
              <div style="line-height: 60px">{{ player.nickname }}</div>

              <div class="user-tool">
                <a-space :size="3">
                  <a @click="beginEditUserHoleScore(player)">修改</a>
                  <a
                    :href="`/game/user-report?gameId=${player.gameTotalScore?.gameId}&userId=${player.id}`"
                    target="_blank"
                  >
                    报告
                  </a>
                  <a @click="viewConfirmPic(player)">图片</a>
                  <a-popover position="right">
                    <a>球童</a>
                    <template #content>
                      <div>
                        <div>{{ player.caddie?.nickname }}</div>
                        <div>{{ player.caddie?.phone }}</div>
                      </div>
                    </template>
                  </a-popover>
                </a-space>
              </div>
            </td>
            <HoleScoreItem
              v-for="hole in holeList.filter((i) => i.holeType === 0)"
              :key="hole.id"
              mode="par"
              :hole="hole"
              :hole-score-list="player.gameHoleScores || []"
              @click="beginEditHoleScore(hole, player, $event)"
            />
            <td class="bold-bg" :rowspan="showDetail ? 5 : 1">
              {{
                player.gameTotalScore?.startNine === null ||
                player.gameTotalScore?.startNine === undefined
                  ? '-'
                  : player.gameTotalScore?.startNine
              }}
            </td>
            <HoleScoreItem
              v-for="hole in holeList.filter((i) => i.holeType === 1)"
              :key="hole.id"
              mode="par"
              :hole="hole"
              :hole-score-list="player.gameHoleScores || []"
              @click="beginEditHoleScore(hole, player, $event)"
            />
            <td class="bold-bg" :rowspan="showDetail ? 5 : 1">
              {{
                player.gameTotalScore?.endNine === null ||
                player.gameTotalScore?.endNine === undefined
                  ? '-'
                  : player.gameTotalScore?.endNine
              }}
            </td>
            <td class="bold-bg" :rowspan="showDetail ? 5 : 1">
              {{
                player.gameTotalScore?.total === null ||
                player.gameTotalScore?.total === undefined
                  ? '-'
                  : player.gameTotalScore?.total
              }}
            </td>
            <td class="bold-bg" :rowspan="showDetail ? 5 : 1">
              {{
                player.gameTotalScore?.pureTotal === null ||
                player.gameTotalScore?.pureTotal === undefined
                  ? '-'
                  : player.gameTotalScore?.pureTotal
              }}
            </td>
          </tr>
          <template v-if="showDetail">
            <tr>
              <HoleScoreItem
                v-for="hole in holeList.filter((i) => i.holeType === 0)"
                :key="hole.id"
                mode="put"
                :hole="hole"
                :hole-score-list="player.gameHoleScores || []"
                @click="beginEditHoleScore(hole, player, $event)"
              />
              <HoleScoreItem
                v-for="hole in holeList.filter((i) => i.holeType === 1)"
                :key="hole.id"
                mode="put"
                :hole="hole"
                :hole-score-list="player.gameHoleScores || []"
                @click="beginEditHoleScore(hole, player, $event)"
              />
            </tr>
            <tr>
              <HoleScoreItem
                v-for="hole in holeList.filter((i) => i.holeType === 0)"
                :key="hole.id"
                mode="penalty"
                :hole="hole"
                :hole-score-list="player.gameHoleScores || []"
                @click="beginEditHoleScore(hole, player, $event)"
              />
              <HoleScoreItem
                v-for="hole in holeList.filter((i) => i.holeType === 1)"
                :key="hole.id"
                mode="penalty"
                :hole="hole"
                :hole-score-list="player.gameHoleScores || []"
                @click="beginEditHoleScore(hole, player, $event)"
              />
            </tr>
            <tr>
              <HoleScoreItem
                v-for="hole in holeList.filter((i) => i.holeType === 0)"
                :key="hole.id"
                mode="kickOffType"
                :hole="hole"
                :hole-score-list="player.gameHoleScores || []"
                @click="beginEditHoleScore(hole, player, $event)"
              />
              <HoleScoreItem
                v-for="hole in holeList.filter((i) => i.holeType === 1)"
                :key="hole.id"
                mode="kickOffType"
                :hole="hole"
                :hole-score-list="player.gameHoleScores || []"
                @click="beginEditHoleScore(hole, player, $event)"
              />
            </tr>
            <tr>
              <HoleScoreItem
                v-for="hole in holeList.filter((i) => i.holeType === 0)"
                :key="hole.id"
                mode="kickOffDirection"
                :hole="hole"
                :hole-score-list="player.gameHoleScores || []"
                @click="beginEditHoleScore(hole, player, $event)"
              />
              <HoleScoreItem
                v-for="hole in holeList.filter((i) => i.holeType === 1)"
                :key="hole.id"
                mode="kickOffDirection"
                :hole="hole"
                :hole-score-list="player.gameHoleScores || []"
                @click="beginEditHoleScore(hole, player, $event)"
              />
            </tr>
            <tr>
              <td class="hole-score" colspan="22">
                <div class="hole-score-stats">
                  <div>
                    <div>老鹰</div>
                    <div>{{ player.gameTotalScore?.eagleCount }}</div>
                  </div>
                  <div>
                    <div>小鸟</div>
                    <div>{{ player.gameTotalScore?.birdieCount }}</div>
                  </div>
                  <div>
                    <div>标准杆</div>
                    <div>{{ player.gameTotalScore?.parCount }}</div>
                  </div>
                  <div>
                    <div>柏忌</div>
                    <div>{{ player.gameTotalScore?.bogeyCount }}</div>
                  </div>
                  <div>
                    <div>双柏忌</div>
                    <div>{{ player.gameTotalScore?.doubleBogeyCount }}</div>
                  </div>
                  <div>
                    <div>打爆</div>
                    <div>{{ player.gameTotalScore?.moreBogeyCount }}</div>
                  </div>
                  <div>
                    <div>上球道率</div>
                    <div>
                      {{
                        player.gameTotalScore?.fairwayRatio !== null &&
                        player.gameTotalScore?.fairwayRatio !== undefined
                          ? (player.gameTotalScore.fairwayRatio * 100).toFixed(
                              2
                            ) + '%'
                          : ''
                      }}
                    </div>
                  </div>
                  <div>
                    <div>上果岭率</div>
                    <div>
                      {{
                        player.gameTotalScore?.greenRatio !== null &&
                        player.gameTotalScore?.greenRatio !== undefined
                          ? (player.gameTotalScore.greenRatio * 100).toFixed(
                              2
                            ) + '%'
                          : ''
                      }}
                    </div>
                  </div>
                  <div>
                    <div>推杆数</div>
                    <div>{{ player.gameTotalScore?.putCount }}</div>
                  </div>
                  <div>
                    <div>微分成绩</div>
                    <div>{{ player.gameTotalScore?.cdwf }}</div>
                  </div>
                </div>
              </td>
            </tr>
          </template>
        </template>
      </table>
    </div>

    <HoleScoreEditor
      v-if="holeScoreConfig.visible"
      :game-id="gameId"
      :user="holeScoreConfig.player"
      :hole="holeScoreConfig.hole"
      :hole-score="holeScoreConfig.holeScore"
      @close="handleEditDone"
    />

    <HoleScoreBatchEditor
      v-if="userHoleScoreConfig.visible"
      :game-id="gameId"
      :player-score="userHoleScoreConfig.playerScore"
      :hole-list="holeList"
      @close="handleUserScoreEditDone"
    />

    <ScoreConfirm
      v-if="confirmConfig.visible"
      :game-id="gameId"
      :user="confirmConfig.player"
      :pic="confirmConfig.pic"
      :player-result="confirmConfig.playerResult"
      :game-result="confirmConfig.gameResult"
      @close="handleConfirmDone"
    />

    <HoleScoreImporter
      v-if="importing"
      :game-id="gameId"
      @close="importing = false"
      @done="handleImportSuccess"
    />
    <HoleScoreImportResult
      v-if="showSignImportResult"
      :list="signImportItemList"
      @close="
        signImportItemList = [];
        showSignImportResult = false;
      "
    />
  </div>
</template>

<style lang="less" scoped>
  .group {
    margin: 12px 0;
    &-header {
      border: 1px solid rgb(var(--gray-3));
      border-bottom: none;
      background: rgb(var(--gray-2));
      padding: 0 12px;
      line-height: 32px;
      border-radius: 3px 3px 0 0;
    }

    table {
      width: 100%;
      border: 1px solid rgb(var(--gray-3));
      td {
        padding: 6px 0;
        text-align: center;
        border-right: 1px solid rgb(var(--gray-3));
        border-bottom: 1px solid rgb(var(--gray-3));
        min-width: 30px;
        &:last-child {
          border-right: none;
        }
      }
      tr:last-child {
        td {
          border-bottom: none;
        }
      }

      .no-border-bottom {
        border-bottom: none;
      }

      .has-right-border {
        border-right: 1px solid rgb(var(--gray-3)) !important;
      }

      .check {
        position: relative;
      }

      .player-result {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        text-align: center;
      }
    }

    .tee {
      position: relative;
      width: 120px;
      span {
        position: absolute;
        left: 3px;
        height: 16px;
        width: 4px;
        border-radius: 3px;
        top: 50%;
        margin-top: -8px;
      }
      .black {
        background: #000;
      }
      .gold {
        background: rgb(var(--gold-5));
      }
      .blue {
        background: rgb(var(--blue-5));
      }
      .white {
        background: rgb(var(--white-5));
        border: 1px solid var(--color-text-4);
      }
      .red {
        background: rgb(var(--red-5));
      }
      .purple {
        background: rgb(var(--purple-5));
      }

      .user-tool {
        position: absolute;
        right: 0;
        bottom: 0;
        font-size: 12px;
        a {
          text-decoration: none;
        }
      }
    }

    .cell1 {
      width: 50px;
    }

    .cell2 {
      width: 100px;
    }

    .cell-t {
      width: 60px;
    }

    .bold-bg {
      font-weight: 600;
      background: rgb(var(--gray-1));
    }

    a {
      color: rgb(var(--primary-6));
      cursor: pointer;
    }
  }

  .hole-score-stats {
    display: flex;
    & > div {
      flex: 1;
      min-width: 0;
      border-right: 1px solid rgb(var(--gray-3));
      &:last-child {
        border-right: none;
      }
      div {
        &:first-child {
          font-size: 12px;
          color: var(--color-text-2);
        }
        &:last-child {
          margin-top: 5px;
        }
      }
    }
  }
</style>
